package com.zhisheng.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zhisheng.Dto.EmpDto;
import com.zhisheng.Dto.EmpLoginDto;
import com.zhisheng.config.MyJwtProperties;
import com.zhisheng.mapper.DeptMapper;
import com.zhisheng.mapper.EmpMapper;
import com.zhisheng.pojo.Dept;
import com.zhisheng.pojo.Emp;
import com.zhisheng.pojo.MyResponseResult;
import com.zhisheng.pojo.PageBean;
import com.zhisheng.service.EmpService;
import com.zhisheng.utils.MyUtilsJwt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Transactional
@Service
public class EmpServiceImpl implements EmpService {

   @Autowired
    private DeptMapper deptMapper;
   @Autowired
    private EmpMapper empMapper;
   @Autowired
   private MyUtilsJwt JwtUtils;
    //查询所有部门
    @Override
    public List<Dept> selectAll() {
        return deptMapper.selectAll();
    }

    @Override
    public PageBean<Emp> getByPage(Integer pageNum, Integer pageSize) {
        /*
        1.先算跳过多少条记录
        2.使用计算好的跳过的记录数，调用mapper获取当前页的数据
        3.调用mapper获取总记录数
        4.封装PageBean并返回
        */
        /*Integer start = (pageNum - 1) * pageSize;
        List<Emp> rows = empMapper.getByPage(start, pageSize);
        Long total = empMapper.getTotal();
        PageBean<Emp> pageBean = new PageBean<>(total, rows);
        return new PageBean<>(total, rows);*/
        /*----------------分页插件----------------------*/
        /*
        1.开启分页插件
        2.正常的查询
        3.直接对原始数据结果进行强转(Page类型的对象)
        4.封装到PageBean中返回结果
        */
        PageHelper.startPage(pageNum, pageSize);
        Page<Emp> rows = (Page)empMapper.getByPage();
        return new PageBean<>(rows.getTotal(), rows.getResult());
    }
    @Override
    public PageBean<Emp> getByPage(Integer pageNum, Integer pageSize, EmpDto empDto) {
        PageHelper.startPage(pageNum, pageSize);
        Page<Emp> rows = (Page)empMapper.getByPage(empDto);
        return new PageBean<>(rows.getTotal(), rows.getResult());
    }

    @Override
    public int deByIds(Integer ids) {
        return empMapper.deByIds(new Integer[]{ids});
    }

    @Override
    public MyResponseResult<String> login(EmpLoginDto dto) {
       Emp emp = empMapper.getByUsernameAndPassword(dto);
       if (emp==null){
           return MyResponseResult.error("NOT_LOGIN");
       }
       //生成令牌，返回令牌
        Map<String,Object> map = new HashMap<>();
       map.put("id",emp.getId());
       map.put("username",emp.getUsername());
       //TODO 生成令牌
        String jwt = JwtUtils.getToken(map);
       return MyResponseResult.ok(jwt);

    }
}
